package org.pp.config;

import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.plugin.*;

import java.sql.Connection;
import java.util.Map;
import java.util.Properties;

@Intercepts({
        @Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class})
})
public class SQLStatsInterceptor implements Interceptor {

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        StatementHandler statementHandler = (StatementHandler) invocation.getTarget();
        // 获取原始的SQL语句
        BoundSql boundSql = statementHandler.getBoundSql();
        String originalSql = boundSql.getSql();
        // 打印原始的SQL语句
        //System.out.println("Original SQL: " + originalSql);
        if(!originalSql.contains("?")){
            System.out.println("Original SQL: " + originalSql);
        }else{
            Object parameterObject = boundSql.getParameterObject();
            if(parameterObject instanceof Map){
                Map<?,?> mp= (Map)parameterObject;
                for (ParameterMapping pmp : boundSql.getParameterMappings()) {
                    originalSql=   originalSql.replaceFirst("\\?",String.valueOf(mp.get(pmp.getProperty())));
                }
            }
            System.out.println("Original SQL: " + originalSql);
            //boundSql.getParameterMappings().forEach();
        }
        // 继续执行原始操作
        return invocation.proceed();
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {
        // 可以在这里接收配置参数
    }
}
